import os
import schedule
import time
import subprocess
import yaml
from queue import Queue
import threading
import re
import websocket
import json

stop_flag = True
change_flag=False

def read_from(file="/data/detect/conf/systemd.yaml"):
    """
    读取 YAML 配置文件，返回字典。
    """
    if not os.path.exists(file):
        print(f"[WARN] 文件不存在: {file}")
        return {}

    try:
        with open(file, "r", encoding="utf-8") as f:
            data = yaml.safe_load(f)
            if data is None:
                data = {}
            return data
    except Exception as e:
        print(f"[ERROR] 读取 YAML 失败: {e}")
        return {}

def save_to(data, file="/data/detect/conf/systemd.yaml"):
    """
    保存字典到 YAML 文件。
    """
    try:
        # 确保目录存在
        os.makedirs(os.path.dirname(file), exist_ok=True)
        with open(file, "w", encoding="utf-8") as f:
            yaml.safe_dump(data, f, allow_unicode=True)
        print(f"[INFO] 配置已保存到 {file}")
    except Exception as e:
        print(f"[ERROR] 保存 YAML 失败: {e}")


def run():
    global stop_flag
    if stop_flag:
        subprocess.call(["/bin/bash", "/data/detect/run.sh"])
        stop_flag=False
        time.sleep(20)

def stop():
    global stop_flag
    if not stop_flag:
        subprocess.call(["/bin/bash", "/data/detect/stop.sh"])
        stop_flag=True
        time.sleep(2)

def load_conf():
        # 从配置读取时间
    conf = read_from()
    start_time = conf.get("startTime", "18:00")
    end_time = conf.get("endTime", "08:00")
    return start_time,end_time

# 调度线程函数
def jobs_thread():
    global stop_flag
    global change_flag
    # 从配置读取时间
    start_time,end_time=load_conf()
    # 设置 schedule 任务（在同一个线程里运行）
    schedule.every().day.at(start_time).do(run)
    schedule.every().day.at(end_time).do(stop)

    print(f"定时任务线程启动，run: {start_time}, stop: {end_time}")

    while True:
        schedule.run_pending()
        time.sleep(2)
        if change_flag:
            schedule.clear()  # 清除所有任务
            stop()
            start_time,end_time=load_conf()
            schedule.every().day.at(start_time).do(run)
            schedule.every().day.at(end_time).do(stop) 
            change_flag=False  
            print("定时任务线程已改变。")


def on_message(ws, message):
    global change_flag
    print("收到消息:", message)
    newdata = json.loads(message)
    save_to(newdata)
    change_flag=True

def on_error(ws, error):
    print("错误:", error)

def on_close(ws, close_status_code, close_msg):
    print("连接关闭")

def on_open(ws):
    print("连接成功")
    # 可以发送数据
    ws.send(json.dumps({"type": "hello"}))

def is_valid_time(s):
    """
    检查字符串是否符合 HH:MM 格式，小时 00-23,分钟 00-59
    """
    pattern = r"^(?:[01]\d|2[0-3]):[0-5]\d$"
    return re.match(pattern, s) is not None


if __name__=="__main__":
    stop()
    run()
    threading.Thread(target=jobs_thread).start()
    url = "ws://htsc.cdldaf.com:8387/ws/50"  
    ws = websocket.WebSocketApp(
        url,
        on_open=on_open,
        on_message=on_message,
        on_error=on_error,
        on_close=on_close
    )
    ws.run_forever()
    # 启动websocket

